from PySide6.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QHeaderView, QTableWidget, QTableWidgetItem, QPushButton, QLabel, QSizePolicy
from PySide6.QtCore import Qt
from ui.components.base.widget import TgBaseWidget
from ui.components.composite.table import TgTable
from ui.components.buttons.button import TgButton
from ui.components.layouts.vbox_layout import TgVBoxLayout
from ui.components.layouts.hbox_layout import TgHBoxLayout
from services.backtest_result_service import BacktestResultService
from datetime import datetime


class BacktestHistoryDialog(QDialog):
    """回测历史记录对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.backtest_result_service = BacktestResultService()
        self.init_ui()
        self.load_history()
    
    def init_ui(self):
        """初始化UI"""
        self.setWindowTitle("回测历史记录")
        self.setFixedSize(1400, 800)
        
        # 主布局
        layout = QVBoxLayout(self)
        
        # 标题
        title_label = QLabel("回测历史记录")
        title_label.setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px;")
        layout.addWidget(title_label)
        
        # 创建表格
        self.history_table = QTableWidget()
        self.setup_table()
        layout.addWidget(self.history_table)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        self.refresh_button = QPushButton("刷新")
        self.refresh_button.clicked.connect(self.load_history)
        
        self.close_button = QPushButton("关闭")
        self.close_button.clicked.connect(self.close)
        
        button_layout.addStretch()
        button_layout.addWidget(self.refresh_button)
        button_layout.addWidget(self.close_button)
        
        layout.addLayout(button_layout)
    
    def setup_table(self):
        """设置表格"""
        # 设置列标题
        headers = [
            "ID", "策略名称", "交易品种", "周期", "开始日期", "结束日期", 
            "总收益率", "年化收益率", "最大回撤", "夏普比率", "创建时间", "策略类文件路径", "操作"
        ]
        
        self.history_table.setColumnCount(len(headers))
        self.history_table.setHorizontalHeaderLabels(headers)
        
        # 设置表格属性
        self.history_table.setAlternatingRowColors(True)
        self.history_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.history_table.setSelectionMode(QTableWidget.SingleSelection)
        
        # 设置列宽
        header = self.history_table.horizontalHeader()
        header.setStretchLastSection(True)
        header.setSectionResizeMode(QHeaderView.Interactive)
        
        # 设置策略类文件路径列为固定宽度，其他列自适应
        header.setSectionResizeMode(11, QHeaderView.Fixed)  # 策略类文件路径列
        self.history_table.setColumnWidth(11, 200)  # 设置为200像素宽度
        
        # 设置样式
        self.history_table.setStyleSheet("""
            QTableWidget {
                gridline-color: #e0e0e0;
                background-color: white;
                alternate-background-color: #f8f9fa;
            }
            QTableWidget::item {
                padding: 8px;
                border: none;
            }
            QTableWidget::item:selected {
                background-color: #0078d4;
                color: white;
            }
            QHeaderView::section {
                background-color: #f1f3f4;
                padding: 8px;
                border: 1px solid #e0e0e0;
                font-weight: bold;
            }
        """)

        # 璁剧疆榛樿琛屽ぇ灏忓拰鏈€灏忚〃闄愬ぇ灏?淇濊瘉鎸夐挳楂樺害鏄剧ず瀹屽叏
        vh = self.history_table.verticalHeader()
        vh.setDefaultSectionSize(36)
        vh.setMinimumSectionSize(32)
    
    def load_history(self):
        """加载历史记录"""
        try:
            # 获取历史记录
            results = self.backtest_result_service.get_all_backtest_results(limit=200)
            
            # 设置表格行数
            self.history_table.setRowCount(len(results))
            
            # 填充数据
            for row, result in enumerate(results):
                # ID
                self.history_table.setItem(row, 0, QTableWidgetItem(str(result.get('id', ''))))
                
                # 策略名称
                self.history_table.setItem(row, 1, QTableWidgetItem(result.get('strategy_name', '')))
                
                # 交易品种
                self.history_table.setItem(row, 2, QTableWidgetItem(result.get('vt_symbol', '')))
                
                # 周期
                self.history_table.setItem(row, 3, QTableWidgetItem(result.get('interval', '')))
                
                # 开始日期
                self.history_table.setItem(row, 4, QTableWidgetItem(result.get('start_date', '')))
                
                # 结束日期
                self.history_table.setItem(row, 5, QTableWidgetItem(result.get('end_date', '')))
                
                # 总收益率
                total_return = result.get('total_return')
                if total_return is not None:
                    return_text = f"{total_return:.2f}%"
                else:
                    return_text = "N/A"
                self.history_table.setItem(row, 6, QTableWidgetItem(return_text))
                
                # 年化收益率
                annual_return = result.get('annual_return')
                if annual_return is not None:
                    annual_text = f"{annual_return:.2f}%"
                else:
                    annual_text = "N/A"
                self.history_table.setItem(row, 7, QTableWidgetItem(annual_text))
                
                # 最大回撤
                max_dd = result.get('max_ddpercent')
                if max_dd is not None:
                    dd_text = f"{max_dd:.2f}%"
                else:
                    dd_text = "N/A"
                self.history_table.setItem(row, 8, QTableWidgetItem(dd_text))
                
                # 夏普比率
                sharpe = result.get('sharpe_ratio')
                if sharpe is not None:
                    sharpe_text = f"{sharpe:.2f}"
                else:
                    sharpe_text = "N/A"
                self.history_table.setItem(row, 9, QTableWidgetItem(sharpe_text))
                
                # 创建时间
                create_time = result.get('create_time', '')
                if create_time:
                    try:
                        # 格式化时间显示
                        dt = datetime.fromisoformat(create_time.replace('Z', '+00:00'))
                        time_text = dt.strftime('%Y-%m-%d %H:%M:%S')
                    except:
                        time_text = create_time
                else:
                    time_text = "N/A"
                self.history_table.setItem(row, 10, QTableWidgetItem(time_text))
                
                # 策略类文件路径
                strategy_file_path = result.get('strategy_file_path', '')
                if not strategy_file_path:
                    strategy_file_path = "N/A"
                self.history_table.setItem(row, 11, QTableWidgetItem(strategy_file_path))
                
                # 操作按钮
                detail_button = QPushButton("显示详情")
                detail_button.clicked.connect(lambda checked, result_id=result.get('id'): self.show_detail(result_id))
                detail_button.setStyleSheet("""
                    QPushButton {
                        background-color: #0078d4;
                        color: white;
                        border: none;
                        padding: 6px 12px;
                        border-radius: 4px;
                        font-size: 12px;
                    }
                    QPushButton:hover {
                        background-color: #106ebe;
                    }
                    QPushButton:pressed {
                        background-color: #005a9e;
                    }
                """)
                # 确保按钮高度与行高匹配，避免文字被裁剪
                detail_button.setMinimumHeight(28)
                detail_button.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Preferred)
                self.history_table.setCellWidget(row, 12, detail_button)
                try:
                    current_height = self.history_table.rowHeight(row)
                    target_height = max(current_height, 36)
                    self.history_table.setRowHeight(row, target_height)
                except Exception:
                    pass
            
            # 调整列宽
            self.history_table.resizeColumnsToContents()
            
        except Exception as e:
            print(f"加载历史记录失败: {e}")
    
    def show_detail(self, result_id):
        """显示详细信息"""
        try:
            result = self.backtest_result_service.get_backtest_result(result_id)
            if result:
                detail_dialog = BacktestDetailDialog(result, self)
                detail_dialog.exec()
        except Exception as e:
            print(f"显示详情失败: {e}")


class BacktestDetailDialog(QDialog):
    """回测详情对话框"""
    
    def __init__(self, result_data, parent=None):
        super().__init__(parent)
        self.result_data = result_data
        self.init_ui()
    
    def init_ui(self):
        """初始化UI"""
        self.setWindowTitle("回测详情")
        self.setFixedSize(800, 600)
        
        layout = QVBoxLayout(self)
        
        # 标题
        title_label = QLabel(f"回测详情 - {self.result_data.get('strategy_name', 'Unknown')}")
        title_label.setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px;")
        layout.addWidget(title_label)
        
        # 创建详情表格
        self.detail_table = QTableWidget()
        self.setup_detail_table()
        layout.addWidget(self.detail_table)
        
        # 关闭按钮
        close_button = QPushButton("关闭")
        close_button.clicked.connect(self.close)
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(close_button)
        layout.addLayout(button_layout)
    
    def setup_detail_table(self):
        """设置详情表格"""
        # 定义所有字段的中文名称
        field_names = {
            'id': 'ID',
            'strategy_name': '策略名称',
            'strategy_file_path': '策略文件路径',
            'vt_symbol': '交易品种',
            'interval': 'K线周期',
            'start_date': '开始日期',
            'end_date': '结束日期',
            'capital': '初始资金',
            'rate': '手续费率',
            'slippage': '滑点',
            'size': '合约乘数',
            'pricetick': '价格跳动',
            'total_days': '总交易日数',
            'profit_days': '盈利天数',
            'loss_days': '亏损天数',
            'end_balance': '期末余额',
            'max_drawdown': '最大回撤金额',
            'max_ddpercent': '最大回撤百分比',
            'max_drawdown_duration': '最大回撤持续天数',
            'total_net_pnl': '总净盈亏',
            'daily_net_pnl': '日均净盈亏',
            'total_commission': '总手续费',
            'daily_commission': '日均手续费',
            'total_slippage': '总滑点',
            'daily_slippage': '日均滑点',
            'total_turnover': '总成交量',
            'daily_turnover': '日均成交量',
            'total_trade_count': '总交易次数',
            'daily_trade_count': '日均交易次数',
            'total_return': '总收益率',
            'annual_return': '年化收益率',
            'daily_return': '日均收益率',
            'win_rate': '胜率',
            'sharpe_ratio': '夏普比率',
            'ewm_sharpe': 'EWM夏普比率',
            'return_std': '收益标准差',
            'return_drawdown_ratio': '收益回撤比',
            'create_time': '创建时间',
            'update_time': '更新时间'
        }
        
        # 过滤有效数据
        valid_data = []
        for key, value in self.result_data.items():
            if value is not None and value != '':
                valid_data.append((key, value))
        
        self.detail_table.setColumnCount(2)
        self.detail_table.setHorizontalHeaderLabels(["指标名称", "数值"])
        self.detail_table.setRowCount(len(valid_data))
        
        # 填充数据
        for row, (key, value) in enumerate(valid_data):
            # 指标名称
            field_name = field_names.get(key, key)
            self.detail_table.setItem(row, 0, QTableWidgetItem(field_name))
            
            # 数值格式化
            formatted_value = self.format_value(key, value)
            self.detail_table.setItem(row, 1, QTableWidgetItem(formatted_value))
        
        # 设置表格属性
        self.detail_table.setAlternatingRowColors(True)
        self.detail_table.setSelectionBehavior(QTableWidget.SelectRows)
        
        # 设置列宽
        header = self.detail_table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        
        # 设置样式
        self.detail_table.setStyleSheet("""
            QTableWidget {
                gridline-color: #e0e0e0;
                background-color: white;
                alternate-background-color: #f8f9fa;
            }
            QTableWidget::item {
                padding: 8px;
                border: none;
            }
            QTableWidget::item:selected {
                background-color: #0078d4;
                color: white;
            }
            QHeaderView::section {
                background-color: #f1f3f4;
                padding: 8px;
                border: 1px solid #e0e0e0;
                font-weight: bold;
            }
        """)
    
    def format_value(self, key, value):
        """格式化数值显示"""
        if value is None:
            return "N/A"
        
        # 百分比字段
        percentage_fields = ['total_return', 'annual_return', 'daily_return', 'max_ddpercent', 'win_rate']
        if key in percentage_fields:
            try:
                return f"{float(value):.2f}%"
            except:
                return str(value)
        
        # 浮点数字段
        float_fields = ['rate', 'slippage', 'pricetick', 'end_balance', 'max_drawdown', 'total_net_pnl',
                       'daily_net_pnl', 'total_commission', 'daily_commission', 'total_slippage',
                       'daily_slippage', 'total_turnover', 'daily_turnover', 'daily_trade_count',
                       'sharpe_ratio', 'ewm_sharpe', 'return_std', 'return_drawdown_ratio']
        if key in float_fields:
            try:
                return f"{float(value):.4f}"
            except:
                return str(value)
        
        # 整数字段
        int_fields = ['capital', 'size', 'total_days', 'profit_days', 'loss_days', 'max_drawdown_duration',
                     'total_trade_count']
        if key in int_fields:
            try:
                return f"{int(value)}"
            except:
                return str(value)
        
        # 时间字段
        time_fields = ['create_time', 'update_time']
        if key in time_fields:
            try:
                dt = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
                return dt.strftime('%Y-%m-%d %H:%M:%S')
            except:
                return str(value)
        
        return str(value)
